﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace Future.Common
{
    public class SingletonProgram
    {
        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);

        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        private const int WS_SHOWNORMAL = 1;

        public static Process GetRunningInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);

            return processes.Length > 1 ? processes[1] : null;
        }

        public static void HandleRunningInstance(Process instance)
        {
            //确保窗子不是最小化或最大化
            ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL);

            //激活进程窗体，使窗体获得焦点
            SetForegroundWindow(instance.MainWindowHandle);
        }
    }
}
